#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define TASK_NUM 10

typedef void (*func_t)();
func_t other_task[TASK_NUM] = {NULL};

void sync_disk()
{
    printf("这是一个刷新数据的任务！\n");
}

void sync_log()
{
    printf("这是一个同步日志的任务！\n");
}

void web_send()
{
    printf("这是一个网络发送的任务！\n");
}

int LoadTask(func_t func)
{
    int i = 0;
    for (; i < TASK_NUM; ++i) 
    {
        if (other_task[i] == NULL) break;
    }
    if (i == TASK_NUM) return -1;
    else other_task[i] = func;
    return 0;
}

void InitTask()
{
    int i = 0;
    for (; i < TASK_NUM; ++i) other_task[i] = NULL;
    LoadTask(sync_disk);
    LoadTask(sync_log);
    LoadTask(web_send);
}

void RunTask()
{
    int i = 0;
    for (i = 0; i < TASK_NUM; ++i)
    {
        if (other_task[i] == NULL) continue;
        other_task[i]();
    }
}

int main()
{
    pid_t ret = fork();
    if (ret == 0)
    {
        int count = 5;
        while (count)
        {
            printf("我是子进程，还有%d秒死，pid=%d, ppid=%d\n", count--, getpid(), getppid());
            sleep(1);
            //int* p = NULL;
            //*p = 100;
        }
        exit(0);
    }
    InitTask();
    while (1)
    {
        int status = 0;
        pid_t ret_id = waitpid(ret, &status, WNOHANG);
        if (ret_id < 0)
        {
            printf("waitpid error!\n");
            exit(1);
        }
        else if (ret_id == 0)
        {
            RunTask();
            sleep(1);
            continue;
        }
        else
        {
            if (WIFEXITED(status))
            {
                printf("wait success, child exit code:%d\n", WEXITSTATUS(status));
            }
            else 
            {
                printf("wait success, child exit signal:%d\n", status & 0x7F);
            }
            //printf("我是父进程，等待子进程成功，pid=%d, ppid=%d, ret_id=%d\n, exit_code=%d, exit_signal=%d\n", 
            //        getpid(), getppid(), ret_id, (status>>8)&0xFF, status&0x7F);
            break;
        }
    }
}
